﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using AspectCore.Extensions.Reflection;
using Microsoft.EntityFrameworkCore;
using netCoreStudy.Attr.QueryAttr;
using netCoreStudy.Entities.Base;
using static netCoreStudy.Express.ReflectorDic;

namespace netCoreStudy.Express
{
	/// <summary>
	/// orderBy  IQueryable 扩展
	/// </summary>
	public static class IncludeExt
	{
		public static IQueryable<TSource> IncludeExp<TSource>(this IQueryable<TSource> query) where TSource : BaseEntity
		{
			Type typeSource = typeof(TSource); // 数据源列表元素对象类型(Student,People)
			// 获取所有 带 include 特性的属性 
			List<PropertyReflector> includeProps = GetPropReflector(typeSource)
				.Where(x => x.GetCustomAttribute<IncludeAttribute>() != null)
				.ToList();
			foreach (PropertyReflector prop in includeProps)
			{
				// 获取 include 特性 
				IncludeAttribute includeAttr = prop.GetCustomAttribute<IncludeAttribute>();
				// fullInclude 为空就 include("User") 否则就 include("FullInclude")
				query = query.Include(includeAttr.FullInclude ?? prop.Name);
			}

			return query;
		}
	}
}